package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Terminal;
import com.ruoyi.system.domain.ValidationGroups.Create;
import com.ruoyi.system.domain.ValidationGroups.Select;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.ITerminalService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;

@Slf4j
@RestController
@RequestMapping("/system/terminal")
public class TerminalController extends BaseController {
    @Autowired
    ITerminalService terminalService;

    @Autowired
    TokenService tokenService;

    @Autowired
    ISysDeptService sysDeptService;

    private AjaxResult checkExistance(Terminal terminal) {
        Map<String, Object> existance = terminalService.findExistance(terminal);
        if (existance != null) {
            Object code_exists = existance.get("code_exists");
            if (code_exists != null && Integer.parseInt(code_exists.toString()) > 0) { 
                return AjaxResult.error(HttpStatus.ERROR, "终端型号已经存在");
            }
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:terminal:add')")
    @PostMapping(value = "/add", produces = "application/json;charset=UTF-8")
    @Log(title = "终端", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody @Validated(Create.class) Terminal terminal) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        terminal.setCompanyId(companyId);
        AjaxResult ret = checkExistance(terminal);
        if (ret != null) {
            return ret;
        }
        Integer id = terminalService.create(terminal);
        if (id != null) {
            return AjaxResult.success(terminal);
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:terminal:list')")
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    public Object index(@Validated(Select.class) Terminal terminal) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("code", terminal.getCode());
        queryVo.filters.put("name", terminal.getName());
        queryVo.filters.put("protocol", terminal.getProtocol());
        queryVo.filters.put("manufacturer", terminal.getManufacturer());
        queryVo.filters.put("remark", terminal.getRemark());
        queryVo.filters.put("company_id", companyId);
        startPage();
        List<Terminal> terminals= terminalService.index(queryVo);
        return getDataTable(terminals);
    }

    @PreAuthorize("@ss.hasPermi('system:terminal:enum')")
    @GetMapping(value = "/enum", produces = "application/json;charset=UTF-8")
    public AjaxResult enumerate() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("company_id", companyId);
        return AjaxResult.success(terminalService.enumerate(queryVo));
    }

    @PreAuthorize("@ss.hasPermi('system:terminal:query')")
    @GetMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieve(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        queryVo.filters.put("company_id", companyId);
        Terminal terminal = terminalService.retrieve(queryVo);
        if (terminal == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        return AjaxResult.success(terminal);
    }

    @PreAuthorize("@ss.hasPermi('system:terminal:edit')")
    @Log(title = "终端", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/edit", produces = "application/json;charset=UTF-8")
    public AjaxResult edit(@RequestBody @Validated(Update.class) Terminal terminal) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", terminal.getId());
        queryVo.filters.put("company_id", companyId);
        Terminal target = terminalService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        terminal.setProtocol(target.getProtocol());
        terminal.setCompanyId(target.getCompanyId());
        AjaxResult ret = checkExistance(terminal);
        if (ret != null) {
            return ret;
        }
        if (terminalService.update(terminal)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:terminal:remove')")
    @Log(title = "终端", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult remove(@PathVariable("id") @NotNull(message = "id不能为null") Integer id)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        queryVo.filters.put("company_id", companyId);
        if (terminalService.delete(queryVo)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
}
